package com.hackerrank.contests.sep13.challenges.sherlockpuzzle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution {
	public static void main(String[] args) throws IOException {
		BufferedReader rdr = new BufferedReader(new InputStreamReader(System.in));
		String input[] = rdr.readLine().split(" ");
		int K = Integer.parseInt(input[0]);
		char S[] = input[1].toCharArray();
		int f[] = new int[5 * S.length], l[] = new int[5 * S.length], cc = 2 * S.length;
		for(int i = 0; i < 5 * S.length; i++) {
			f[i] = -2;
			l[i] = -3;
		}
		f[cc] = l[cc] = -1;
		for(int i = 0; i < S.length; i++) {
			if(S[i] == '1')
				cc += 3;
			else
				cc -= 2;
			if(f[cc] < -1)
				f[cc] = i;
			l[cc] = i;
		}
		int d = cc - 2 * S.length;
		// case 1: all K repetitions included
		if(d >= 0) {
			System.out.println(S.length * K);
			return;
		}
		// case 2: K - 1 repetitions
		// case 2.1: maximum starting subsequence
		int sd = d, msl = -1;
		if(d * (K - 1) + sd >= 0)
			msl = S.length;
		else {
			for(int i = S.length - 1; i >= 0; i--) {
				if(S[i] == '1')
					sd += 3;
				else
					sd -= 2;
				if(d * (K - 1) + sd >= 0)
					msl = i;
			}
		}
		// case 2.2: maximum ending subsequence
		int ed = d, mel = -1;
		if(d * (K - 1) + ed >= 0)
			mel = S.length;
		else {
			for(int i = 0; i < S.length; i++) {
				if(S[i] == '1')
					ed += 3;
				else
					ed -= 2;
				if(d * (K - 1) + ed >= 0)
					mel = S.length - i - 1;
			}
		}
		// case 2.3: the best of starting and ending subsequences
		int max = Math.max(msl, mel);
		if(max >= 0) {
			System.out.println(S.length * (K - 1) + max);
			return;
		}
		// case 3: < K - 1 repetitions
		// case 3.1: find maximum repetitions that can be considered
		int p = 0, pl = 0, cs = 0, css = 0;
		for(int i = 0; i < S.length; i++) {
			if(cs > 0) {
				cs = 0;
				css = i;
			}
			if(S[i] == '1') {
				cs += 3;
			} else {
				cs -= 2;
				if(cs < p) {
					p = cs;
					pl = i - css + 1;
				}
			}
		}
		int nr = 1 - p / d;
		if(p % d != 0)
			nr--;
		if(nr >= 0) {
			// case 3.2: find subsequence with sum <= d * ( nr + 1) and minimum length
			int m = -1, md = -1, t = d * (nr + 1);
			for(int i = 0; i < S.length; i++) {
				if(l[i] < -1)
					continue;
				if(l[i] < m)
					m = l[i];
				int cd = m - f[i];
				if(cd > md)
					md = cd;
			}
			System.out.println(S.length * (nr + 1) - pl);
			return;
		}
		// case 4: part of single repetition
		int m = -1, md = -1;
		for(int i = l.length - 1; i >= 0; i--) {
			if(l[i] < -1)
				continue;
			if(l[i] > m)
				m = l[i];
			int cd = m - f[i];
			if(cd > md)
				md = cd;
		}
		System.out.println(md);
	}
}
